package com.liao.cloudstorage.controller;

import com.alibaba.fastjson.JSON;
import com.liao.cloudstorage.entity.Bucket;
import com.liao.cloudstorage.service.IBucketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

import static com.liao.cloudstorage.conf.CodeInfo.ERROR;
import static com.liao.cloudstorage.conf.CodeInfo.SUCCESS;

@Controller
public class BucketController {

    private final IBucketService bucketService;

    @Autowired
    public BucketController(IBucketService bucketService) {
        this.bucketService = bucketService;
    }

    @GetMapping("/storageList")
    public String getAllBuckets(ModelMap modelMap) {
        List<Bucket> bucketList = bucketService.getAllBucket();
        modelMap.addAttribute("bucketList", bucketList);
        return "storageList";
    }

    @ResponseBody
    @PostMapping("/bucket/delete/")
    public Object deleteBucket(Integer id) {
        ModelMap modelMap = new ModelMap();
        boolean b = bucketService.deleteBucketById(id);
        if (b) {
            modelMap.addAttribute("code", SUCCESS);
            modelMap.addAttribute("info", "删除成功");
        } else {
            modelMap.addAttribute("code", ERROR);
            modelMap.addAttribute("info", "删除失败");
        }
        return JSON.toJSON(modelMap);
    }

    @GetMapping("/createBucket/")
    public String bucketPage(){
        return "createBucket";
    }
    @ResponseBody
    @PostMapping("/createBucket/")
    public Object createBucket(String bucketName){
        boolean b = bucketService.addBucket(bucketName);
        ModelMap modelMap = new ModelMap();
        if (b){
            modelMap.addAttribute("code",SUCCESS);
            modelMap.addAttribute("info","添加成功");
        }else {
            modelMap.addAttribute("code",ERROR);
            modelMap.addAttribute("info","添加失败");
        }
        return JSON.toJSON(modelMap);
    }

}
